package com.crm.web.action;


import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.crm.domain.Customer;
import com.crm.domain.PageBean;
import com.crm.service.CustomerService;
import com.crm.utils.UploadUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {
	private Customer customer = new Customer();
	
	@Override
	public Customer getModel() {
		return customer;
	}

	// 注入Service
	private CustomerService customerService;
	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}
	
	// 接收当前页数据（默认为1）
	private Integer currPage = 1;
	public void setCurrPage(Integer currPage) {
		if (currPage == null) {
			currPage = 1;
		}
		this.currPage = currPage;
	}
	
	// 接收每页显示数据（默认为3）
	private Integer pageSize = 3;
	public void setPageSize(Integer pageSize) {
		if (pageSize == null) {
			pageSize = 1;
		}
		this.pageSize = pageSize;
	}
	
	/**
	 * 文件上传的三个属性
	 * 使用sturts2的文件上传
	 */
	private String uploadFileName;		// 上传文件的名称
	private String uploadContentType; 	// 上传的文件类型
	private File upload;				// 上传的文件
	
	public void setUpload(File upload) {
		this.upload = upload;
	}
	
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	
	// 跳转到添加客户页面
	public String saveUI(){
		return "saveUI";
	}
	
	// 保存客户信息到数据库
	public String save() throws IOException{
		// 保存用户上传的图片
		// 判断是否上传了文件
		if(upload != null){
			// 保存上传文件的路径
			String path = "D:/WebServer/upload";
			// 生成唯一文件名
			String uuidFileName = UploadUtils.getUuidFileName(uploadFileName);
			String realPath = UploadUtils.getPath(uuidFileName);
			String url = path + realPath;
			File file = new File(url);
			// 判断文件路径是否存在
			if(!file.exists()){
				// 创建该路径
				file.mkdirs();
			}
			// 文件上传
			File destFile = new File(url + "/" + uuidFileName);
			FileUtils.copyFile(upload, destFile);
			// 将上传文件的路径添加到数据库
			customer.setCust_image(url + "/" + uuidFileName);
		}
		
		// 调用service保存
		customerService.save(customer);
		return "saveSuccess";
	}
	
	// 查询所有客户
	public String findAll(){
		// 接收分页参数
		// 最好使用DetachedCriteria对象（条件查询--带分页）
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Customer.class);
		// 接收条件查询的参数
		// 模糊查询名字
		if(customer.getCust_name() != null && !"".equals(customer.getCust_name())){
			detachedCriteria.add(Restrictions.like("cust_name", "%" + customer.getCust_name() + "%"));
		}
		// 客户来源
		if (customer.getBaseDictSource() != null) {
			if (customer.getBaseDictSource().getDict_id() != null && !"".equals(customer.getBaseDictSource().getDict_id())) {
				detachedCriteria.add(Restrictions.eq("baseDictSource.dict_id", customer.getBaseDictSource().getDict_id()));
			}
		}
		// 客户级别
		if (customer.getBaseDictLevel() != null) {
			if (customer.getBaseDictLevel().getDict_id() != null && !"".equals(customer.getBaseDictLevel().getDict_id())) {
				detachedCriteria.add(Restrictions.eq("baseDictLevel.dict_id", customer.getBaseDictLevel().getDict_id()));
			}
		}
		// 客户行业
		if (customer.getBaseDictIndustry() != null) {
			if (customer.getBaseDictIndustry().getDict_id() != null && !"".equals(customer.getBaseDictIndustry().getDict_id())) {
				detachedCriteria.add(Restrictions.eq("baseDictIndustry.dict_id", customer.getBaseDictIndustry().getDict_id()));
			}
		}
		

		// 调用业务层，进行分页查询
		PageBean<Customer> pageBean = customerService.findByPage(detachedCriteria, currPage, pageSize);
		// 返回分页容器到浏览器
		ActionContext.getContext().getValueStack().push(pageBean);
		return "findAll";
	}
	
	// 删除客户
	public String delete(){
		// 根据id查询客户
		customer = customerService.findById(customer.getCust_id());
		// 删除服务器中的图片文件
		String img_location = customer.getCust_image();
		if (img_location != null && !"".equals(img_location)) {
			File file = new File(img_location);
			if (file.exists()) {
				file.delete();
			}
		}
		// 删除数据库中的信息
		customerService.delete(customer);
		return "deleteSuccess";
	}
	
	// 修改客户信息(跳转到修改页面)
	public String editUI(){
		customer = customerService.findById(customer.getCust_id());
		return "editUI";
	}
	
	// 保存用户提交的修改信息
	public String update() throws IOException{
		// 判断用户是否有重新上传文件
		// 判断是否重新上传文件
		if(upload != null){
			// 删除原有的文件
			String cust_image = customer.getCust_image();
			if(cust_image != null && !"".equals(cust_image)){
				File file = new File(cust_image);
				if(file.exists()){
					file.delete();				
				}
			}
			
			// 保存上传文件的路径
			String path = "D:/WebServer/upload";
			// 生成唯一文件名
			String uuidFileName = UploadUtils.getUuidFileName(uploadFileName);
			// 生成目录
			String realPath = UploadUtils.getPath(uuidFileName);
			String url = path + realPath;
			File file = new File(url);
			// 判断文件路径是否存在
			if(!file.exists()){
				// 创建该路径
				file.mkdirs();
			}
			// 文件上传
			File destFile = new File(url + "/" + uuidFileName);
			FileUtils.copyFile(upload, destFile);
			// 修改数据库中文件路径
			// 将上传文件的路径添加到数据库
			customer.setCust_image(url + "/" + uuidFileName);
			
		}

		// 调用业务层，修改客户信息
		customerService.update(customer);

		return "updateSuccess";
	}
	
	// 客户拜访记录-添加客户拜访记录-查询所有客户
	public String findAllCustomer() throws IOException{
		// 查询得到所有客户
		List<Customer> list = customerService.findAll();
		// 将list转成json
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setExcludes(new String[]{"linkMans", "baseDictSource", "baseDictIndustry", "baseDictLevel"});
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		// 返回json数组到浏览器
		ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
		ServletActionContext.getResponse().getWriter().println(jsonArray.toString());
		return NONE;
	}
	
	

}
